dodov
dodov

Reputation: 5844

Remove irrelevant files with post-receive hook

I’m using a bare Git repo and automate deployment via hooks. I’ve set up a git remote locally that I can push to and the server updates the files automatically.

However, I’m using Kirby CMS which is a file-based CMS, meaning any unnecessary files should be removed. Basically, the folder in which my hook does git checkout should be identical to the state of the repo.

Here’s my hook script:

#!/bin/sh
git --work-tree=/var/www/html/myrepo --git-dir=/var/repo/myrepo checkout -f
cd /var/www/html/myrepo/assets
npm install --production

I’ve read about git clean, but as far as I understand, it can be used on repos with a work tree, which my bare repo doesn’t have.

How would I do this?

Upvotes: 0

Views: 171

Answers (1)

drRobertz
drRobertz

Reputation: 3638

First, after running git-checkout in the hook script you do have a working tree, it is just in a separate directory from the bare repo.

Second, the script you have will remove files that are under the control of git, when they are removed from the repo (e.g., with git rm).

That said, if you want to also remove any locally created files from your working tree, you can do that by adding git clean to the same hook script, after the checkout:

git --work-tree=/var/www/html/myrepo --git-dir=/var/repo/myrepo clean -fd

where -f means force and -d means also remove directories (but do read the manual before doing this in any real environment). To test it you can give the -n (dry run) option which will not remove anything but just print what it would remove, i.e.:

git --work-tree=/var/www/html/myrepo --git-dir=/var/repo/myrepo clean -nd

Edit: as commented by @jthill, git-clean has further options (-e, -x, -X) for selectively removing untracked files based on combinations of a given pattern and .gitignore (see the manual for details).

Upvotes: 2

Related Questions