Search code examples
gitgitlabjekyllgithooks

How can I automate copy operations before Git commits?


Context: I want to create a Jekyll collaborative blog. I created a subtree to insulate the collaborative portion of it from the rest of the site. However, as those goes into _posts, any blobs there are ignored when Jekyll renders the site.

Now, what I do is to copy everything from a specific folder (_posts/assets/) to assets/, so Jekyll can use those files after rendering the site.

I'm using Gitlab to host Jekyll, so I need to have this before pushing to Gitlab, so I do manually this now by do

cp -R _posts/assets/* assets
git add -A
git commit "New files for articles"

Can I put this on pre-commit hook so I can automate this process? Any tips?


Solution

  • Take a look at the git hooks available to you:

    $ cd ~/project_name
    $ ls -1 .git/hooks/
    applypatch-msg.sample
    commit-msg.sample
    fsmonitor-watchman.sample
    post-update.sample
    pre-applypatch.sample
    pre-commit.sample
    pre-merge-commit.sample
    prepare-commit-msg.sample
    pre-push.sample
    pre-rebase.sample
    pre-receive.sample
    update.sample
    

    You're saying you want to execute a script pre-push (before pushing to GitLab). So, create a pre-push git hook script, and make it executable.

    $ touch .git/hooks/pre-push
    $ chmod +x .git/hooks/pre-push
    

    Then, put your commands in that file.

    .git/hooks/pre-push:

    #!/bin/sh
    
    cp -R _posts/assets/* assets
    git add -A
    git commit "New files for articles"
    exit 0