Skip to content

Instantly share code, notes, and snippets.

@JJ
Created August 26, 2013 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JJ/6343935 to your computer and use it in GitHub Desktop.
Save JJ/6343935 to your computer and use it in GitHub Desktop.
Git post-commit hook for modifying .md files to work with gh-pages and just copy other files, like .png, .css and so on.
#!/usr/bin/env perl
use strict;
use warnings;
use v5.14;
use Git::Hooks;
use File::Slurp qw(read_file write_file);
my $layout_preffix=<<EOT;
---
layout: index
---
EOT
POST_COMMIT {
my ($git) = @_;
my $branch = $git->command(qw/rev-parse --abbrev-ref HEAD/);
if ( $branch =~ /master/ ) {
my $changed = $git->command(qw/show --name-status/);
my @changed_files = ($changed =~ /\s\w\s+(\S+)/g);
my @mds = grep ( /\.md/, @changed_files );
my @copies = grep( /(\.png|\.jpg)/, @changed_files );
#Now change branch and process
#Inspired by http://stackoverflow.com/questions/15214762/how-can-i-sync-documentation-with-github-pages
$git->command(qw/checkout gh-pages/);
for my $f ( @mds ) {
$git->command( 'checkout', 'master', '--', $f );
my $file_content = read_file( $f );
$file_content =~ s/\.md\)/\)/g; # Change links
$file_content = $layout_preffix.$file_content;
if ( $f ne 'README.md' ) {
write_file($f, $file_content);
$git->command('add', $f );
} else {
write_file('index.md', $file_content );
$git->command('add', 'index.md' );
unlink('README.md');
}
say "Processing $f";
}
for my $c (@copies ) {
$git->command( 'checkout', 'master', '--', $c );
$git->command('add', $c );
say "Copying $c";
}
$git->command('commit','-a', '-m', "Sync ".
join( " ", @mds)." and ".
join( " ", @copies)." from master to gh-pages");
$git->command(qw/checkout master/); #back to original
}
};
run_hook($0, @ARGV);
=head1 NAME
git-hooks.pl - post-commit hooks to sync markdown pages with GitHub pages
=head2 SYNOPSIS
First you need to install C<Git::Hooks> and C<File::Slurp>. I use say,
so you will need perl > 5.10. Besides, you need to locate Git.pm and
copy it where the file can find it. That depends on the OS and perl
installation you're using (I use perlbrew), In my case it was:
bash% cp /usr/share/perl5/Git.pm ~/perl5/perlbrew/perls/perl-5.16.1/lib/site_perl/5.16.1/
Then copy git-hooks.pl to .git/hooks, make it runnable (chmod +x
git-hooks) and then
bash% ln -s git-hooks.pl post-commit
Any trouble, just check the L<Git::Hooks> manual.
=head1 LICENSE
This is released under the Artistic
License. See L<perlartistic>.
=head2 AUTHOR
JJ Merelo, L<jj@merelo.net>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment